/*********************************************************************************
 *      Copyright:  (C) 2020 YangZhengQing<2489833081@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  connect_client.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/08/2020)
 *         Author:  YangZhengQing <2489833081@qq.com>
 *      ChangeLog:  1, Release initial version on "04/08/2020 03:31:19 PM"
 *                 
 ********************************************************************************/

#include "../include/server.h"

/*功能：连接新客户端
 *参数：epollfd：传入一个epoll实例
        sockfd：传入套接字
 *返回值：成功返回0，失败返回-1*/
int connect_client(int epollfd,int sockfd)
{
    int                           connectfd = -1;
    struct sockaddr_in            client_addr;//保存客户端信息
    socklen_t                      client_len;
    struct epoll_event            event;//保存文件描述符属性

    connectfd = accept(sockfd,(struct sockaddr *)&client_addr,&client_len);//接收请求
    if(connectfd < 0)
    {
        printf("accept client[%s:%d] error:%s\n",inet_ntoa(client_addr.sin_addr),client_addr.sin_port,strerror(errno));
        return -1;

    }
    else
    {
        printf("client[%s:%d][%d] connecting successfully!\n",inet_ntoa(client_addr.sin_addr),client_addr.sin_port,connectfd);
    }

    /* 设置新连接上的文件描述符属性*/
    event.data.fd = connectfd;
    event.events = EPOLLIN;//设置为水平触发模式
    epoll_ctl(epollfd,EPOLL_CTL_ADD,connectfd,&event);//将新的fd添加到epoll监听的队列中*/

    return 0;

}


int setnonblocking(int sock)//根据文件描述符操作文件特性
{
    int opts;
    opts = fcntl(sock,F_GETFL);//获取文件标记
    if(opts < 0)
    {
        printf("fcntl F_GETL error:%s\n",strerror(errno));
        return -1;
    }

    opts |= O_NONBLOCK;

    if(fcntl(sock,F_SETFL,opts) < 0)//设置文件标记
    {
        printf("fcntl F_SETL ERROR:%s\n",strerror(errno));
        return -1;
    }

    return 0;
}
